package com.example.main;

import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;


public class ScanGunActivity2 extends FragmentActivity {
    private USB_Admin usb_admin;
    private UsbManager usbManager;
    private UsbDevice usbDevice;
    private UsbInterface usbInterface;
    private UsbDeviceConnection usbDeviceConnection;
    private UsbEndpoint usbEndpointIn;
    private UsbEndpoint usbEndpointOut;

    protected final Object mReadBufferLock = new Object();
    protected final Object mWriteBufferLock = new Object();


    byte[] receiveBytes = new byte[32];
    byte[] sendBytes = new byte[32];

    private StringBuffer stringBuffer = new StringBuffer();

    TextView content;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_gun);


        content = (TextView) findViewById(R.id.content);

        usb_Init();

        usb_receiveData();

        //usb_sendData();

    }

    public void usb_Init() {

        Intent intent = getIntent();
        usb_admin = new USB_Admin(this);
        Log.v("usb_admin: ", "" + usb_admin);
        usbManager = usb_admin.get_UsbManager();
        Log.v("usbManager: ", "" + usbManager);
        usbDevice = usb_admin.get_UsbDevice(intent);
        Log.v("usbDevice: ", "" + usbDevice);
        Log.v("interfaceCount: ", "" + usbDevice.getInterfaceCount());
        usbInterface = usb_admin.get_Interface(this);
        Log.v("usbInterface: ", "" + usbInterface);    //1个；
        Log.v("usbEndpointCount: ", "" + usbInterface.getEndpointCount());

        usbEndpointIn = usb_admin.get_Endpoint(0, this);
        Log.v("usbEndpointIn: ", "" + usbEndpointIn);
        Log.v("usbEndpointDirection: ", "" + usbEndpointIn.getDirection());

        usbEndpointOut = usb_admin.get_Endpoint(1, this);
        Log.v("usbEndpointOut: ", "" + usbEndpointOut);
        Log.v("usbEndpointDirection: ", "" + usbEndpointOut.getDirection());

        usbDeviceConnection = usb_admin.get_usbDeviceConnection(this);
        Log.v("usbDeviceConnection: ", "" + usbDeviceConnection);
//        configUsb340(115200);
        configUsb340(9800);

    }

    public void usb_receiveData() {


        ReceiveThread receiveThread = new ReceiveThread();
        Thread thread = new Thread(receiveThread);
        thread.start();

    }


    public void usb_sendData() {

        SendThread sendThread = new SendThread();
        Thread send = new Thread(sendThread);
        send.start();

    }

    class ReceiveThread implements Runnable {

        @Override
        public void run() {
            synchronized (mReadBufferLock) {
                while (!Thread.currentThread().isInterrupted()) {
                    if (usbDeviceConnection.claimInterface(usbInterface, true)) {

                        if ((usb_admin.receive_Message(receiveBytes)) >= 0) {

                        /*
                        for(int i=0;i<receiveBytes.length;i++){
                            Log.v("Data: ",""+receiveBytes[i]);   //为什么这里得到的数据大部分都为0呢？
                        }
                        */
                            Log.v("length: ", "" + usb_admin.receive_Message(receiveBytes));
                            String string = null;
                            Log.v("receiveBytes: ", "" + receiveBytes.toString());
                            Log.v("receiveBytes: ", "is OK ");
                            try {
                                string = new String(receiveBytes, "UTF-8");
                                stringBuffer.append(string);
                                Log.v("3D DATA", string);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            Message message = handler.obtainMessage();
                            message.obj = stringBuffer;
                            message.what = 1;
                            handler.sendMessage(message);

                        } else {

                            Log.v("Receive Data: ", "failed");

                        }

                    } else {

                        Log.v("claimInterface: ", "failed");
                    }

                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }


        }
    }

    class SendThread implements Runnable {

        @Override
        public void run() {

            synchronized (mWriteBufferLock) {

                while (!Thread.currentThread().isInterrupted()) {

                    if (usbDeviceConnection.claimInterface(usbInterface, true)) {

                        String string = " Android USB Test ";
                        sendBytes = string.getBytes();
                        if ((usb_admin.send_Message(sendBytes)) >= 0) {

                            Log.v("sendBytes: ", "is OK ");

                        } else {

                            Log.v("Send Data: ", "failed");

                        }

                    } else {

                        Log.v("claimInterface: ", "failed");
                    }

                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }


        }
    }


    private android.os.Handler handler = new android.os.Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    content.setText((StringBuffer) msg.obj);
                    break;

                default:
                    break;

            }


        }
    };


    private boolean configUsb340(int paramInt) {
        byte[] arrayOfByte = new byte[8];
        usbDeviceConnection.controlTransfer(192, 95, 0, 0, arrayOfByte, 8, 1000);
        usbDeviceConnection.controlTransfer(64, 161, 0, 0, null, 0, 1000);
        long l1 = 1532620800 / paramInt;
        for (int i = 3; ; i--) {
            if ((l1 <= 65520L) || (i <= 0)) {
                long l2 = 65536L - l1;
                int j = (short) (int) (0xFF00 & l2 | i);
                int k = (short) (int) (0xFF & l2);
                usbDeviceConnection.controlTransfer(64, 154, 4882, j, null, 0, 1000);
                usbDeviceConnection.controlTransfer(64, 154, 3884, k, null, 0, 1000);
                usbDeviceConnection.controlTransfer(192, 149, 9496, 0, arrayOfByte, 8, 1000);
                usbDeviceConnection.controlTransfer(64, 154, 1304, 80, null, 0, 1000);
                usbDeviceConnection.controlTransfer(64, 161, 20511, 55562, null, 0, 1000);
                usbDeviceConnection.controlTransfer(64, 154, 4882, j, null, 0, 1000);
                usbDeviceConnection.controlTransfer(64, 154, 3884, k, null, 0, 1000);
                usbDeviceConnection.controlTransfer(64, 164, 0, 0, null, 0, 1000);
                return true;
            }
            l1 >>= 3;
        }
    }


}

